package com.pg.agent.engine.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.pg.agent.engine.client.common.AgentConstant;
import com.pg.agent.engine.client.common.enums.ChatTypeEnum;
import com.pg.agent.engine.client.component.BubbleComponent;
import com.pg.agent.engine.client.dto.ComponentInParamVO;
import com.pg.agent.engine.client.dto.AgentExeDTO;
import com.pg.agent.engine.client.message.InPutMessage;
import com.pg.agent.engine.client.message.OutPutMessage;
import com.pg.agent.engine.client.model.*;
import com.pg.agent.engine.client.model.action.Action;
import com.pg.agent.engine.client.model.agent.AIAgent;
import com.pg.agent.engine.client.model.agent.AgentActionBO;
import com.pg.agent.engine.client.model.environment.AIEnvironment;
import com.pg.agent.engine.client.model.llm.CallLog;
import com.pg.agent.engine.client.model.sop.AISOP;
import com.pg.agent.engine.client.model.sop.IntentRecognition;
import com.pg.agent.engine.client.model.sop.Memory;
import com.pg.agent.engine.client.model.state.AIState;
import com.pg.agent.engine.service.common.cache.SessionManager;
import com.pg.agent.engine.service.service.AIAgentService;
import com.pg.agent.engine.service.service.AIEnvironmentService;
import com.pg.agent.engine.service.service.AIRunService;
import com.pg.agent.engine.service.service.AISOPService;
import com.pg.agent.engine.service.utils.SessionConnectManager;
import com.pg.agent.engine.service.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
@Slf4j
@Service("aiRunService")
public class AIRunServiceImpl implements AIRunService {

    /**
     * 设置失效时间30天
     */
    private static final Integer expireTime = 60 * 60 * 24 * 30;
    @Resource
    private AIEnvironmentService aiEnvironmentService;
    @Resource
    private AISOPService aiSopService;
    @Resource
    private AIAgentService aiAgentService;


    private static void dealChat(AgentExeDTO runSopDTO, AIEnvironment aiEnvironment) {


        if (runSopDTO.getDealMode() == null || ChatTypeEnum.CANCEL.getCode().equals(runSopDTO.getDealMode())) {
            return;
        }
        List<Memory> memoryList = aiEnvironment.getShareMemory().getLongMemory();

        int len = memoryList.size();
        if (len == 0) {
            return;
        }

        if (len >= 2) {
            for (int i = 0; i < 2; i++) {
                Memory memory = memoryList.get(len - i - 1);
                if ("user".equalsIgnoreCase(memory.getSendName())) {
                    memoryList.remove(len - i - 1);
                    if (ChatTypeEnum.REANSWER.getCode().equals(runSopDTO.getDealMode())) {
                        runSopDTO.setContent(memory.getContent());
                    }
                    break;
                } else {
                    memoryList.remove(len - i - 1);
                }
                if (i == 1) {
                    if (ChatTypeEnum.REANSWER.getCode().equals(runSopDTO.getDealMode())) {
                        runSopDTO.setContent(memory.getContent());
                    }
                }
            }
        } else {
            Memory memory = memoryList.get(0);
            memoryList.remove(0);
            if ("user".equalsIgnoreCase(memory.getSendName())) {
                if (ChatTypeEnum.REANSWER.getCode().equals(runSopDTO.getDealMode())) {
                    runSopDTO.setContent(memory.getContent());
                }
            }
        }
    }

    @Override
    public AgentExeDTO startSOP(AgentExeDTO agentExeDTO) {

        String sopKey = AgentConstant.AGENT_PREFIX + agentExeDTO.getSopId()+(agentExeDTO.isDebug()?("-" + agentExeDTO.getSopVersionId()):"");

        SessionObject sessionObject = SessionManager.getSession(sopKey);
        if (sessionObject != null) {
            String sessionId = generateSessionId(agentExeDTO);
            sessionObject.setSessionId(sessionId);
            sessionObject.setUserId(agentExeDTO.getUserId());

            // 存放到redis缓存
            log.info("key:{},managerObject:[{}]", sopKey + ":" + sessionId, JSONObject.toJSONString(sessionObject));
            SessionManager.addSession(sopKey + ":" + sessionId,sessionObject);
            agentExeDTO.setSessionId(sessionObject.getSessionId());

            //判断是否有初始问句
            String beginQuery = sessionObject.getAiSOP().getBeginQuery();
            log.info("beginQuery={}", beginQuery);
            if (ObjectUtil.isNotEmpty(beginQuery)) {
                OutPutMessage outPutMessage = new OutPutMessage();
                outPutMessage.setContent(beginQuery);
                outPutMessage.setLabelList(JSONObject.toJSONString(sessionObject.getAiSOP().getLabelList()));
                agentExeDTO.setSOPCallVO(outPutMessage);
            }
            return agentExeDTO;
        }
        return null;
    }


    @Override
    public void endSOP(AgentExeDTO runSopDTO) {
        String userKey = AgentConstant.AGENT_PREFIX + runSopDTO.getSessionId();
        // 删除redis缓存
        SessionManager.removeSession(userKey);
    }


    @Override
    public void dialogueRunSOPStream(AgentExeDTO runSopDTO, HttpServletResponse response, SessionObject sessionObject, String userKey) {
        //初始化数据
        Date sopStartTime = new Date();
        AISOP aiSOP = sessionObject.getAiSOP();
        AIEnvironment aiEnvironment = sessionObject.getAiEnvironment();
        runSopDTO.setSessionId(sessionObject.getSessionId());
        dealChat(runSopDTO, aiEnvironment);
        long beginTime = System.currentTimeMillis();
        boolean inParamFlag = runSopDTO.isInParamFlag();
        boolean repeat = runSopDTO.isRepeat();
        OutPutMessage outMessage = new OutPutMessage(sessionObject.getSessionId(), sessionObject.getExeNum());
        InPutMessage inPutMessage = new InPutMessage(aiEnvironment, sessionObject, userKey, runSopDTO);

        if (!inParamFlag && !repeat) {
            sessionObject.exeTotal();
            //保存用户提问的历史记录
            Memory memory = new Memory(sessionObject.getExeNum(), inPutMessage.getDataId(), "User", "User", runSopDTO.getContent(), runSopDTO.getContent());
            aiEnvironmentService.updateMemory(inPutMessage, memory, sessionObject);
            CallLog callLog = new CallLog();
            callLog.setResponse(runSopDTO.getContent());
            //新增sop记录
            insertSessionRecord(runSopDTO, inPutMessage.getSessionId(), sopStartTime);

            insertSessionDetailLog(new ArrayList<>(), runSopDTO.getImageList(), runSopDTO.getFileList(), JSONObject.toJSONString(Arrays.asList(runSopDTO.getBubbleComponent())), callLog, inPutMessage, beginTime, true, runSopDTO, sessionObject.getExeNum());

            SessionManager.addSession(userKey, sessionObject);
        }

        AIAgent currentAgent = null;
        AIState currentState = null;
        try {
            //判断当前的agent是否需要参数，如果需要，直接返回，如果不需要，则继续往下走
            if (runSopDTO.getBubbleComponent() != null) {
                BubbleComponent bubbleComponent = runSopDTO.getBubbleComponent();
                if (bubbleComponent.getType() == 1) {
                    String stateName = bubbleComponent.getStateName();
                    String agentName = bubbleComponent.getAgentName();
                    AIState aiState = aiSOP.getStates().get(stateName);
                    if (aiState == null) {
                        Utils.outputStreamResult(1000, "气泡组件没有找到对应的场景", true, runSopDTO.getDataId(), response);
                        return;
                    }
                    AIAgent agent = aiState.getAgent(agentName);

                    if (agent == null) {
                        Utils.outputStreamResult(1000, "气泡组件没有找到对应的agent", true, runSopDTO.getDataId(), response);
                        return;
                    }
                    currentState = aiState;
                    currentAgent = agent;
                    inPutMessage.setAgent(currentAgent);
                    inPutMessage.setState(currentState);
                } else {
                    Utils.outputStreamResult(1000, "气泡组件参数错误", true, runSopDTO.getDataId(), response);
                    return;
                }
            } else if (!inParamFlag && !repeat) {
                sessionObject.exeTotal();
                AIState state = inPutMessage.getSop().getCurrentState();
                if (state != null) {
                    AIAgent agent = state.getAgent(state.getCurrentAgent());
                    if (agent != null) {
                        agent.getExecComponentInParam().clear();
                        agent.getExecComList().clear();
                        agent.getComponentResult().clear();
                    }
                }
                aiSopService.next(inPutMessage, sessionObject, response);

                currentAgent = inPutMessage.getAgent();
                currentState = inPutMessage.getState();

                // 判断操作流程是否结束
                if (aiSOP.isFinished()) {
                    log.info("SOP finished!");
                    sessionObject.setExeNum(0);
                    Utils.outputStreamResult(null, runSopDTO.getDataId(), true, outMessage, response);
                    return;
                }
                if (currentState == null) {
                    IntentRecognition recognition = aiSOP.getIntentRecognition();
                    Integer type = recognition.getDefaultIntentType();
                    if (type != null && type == 2) {
                        currentState = aiSOP.getStates().get(recognition.getAnswerList().get(0));
                        int size = inPutMessage.getCallLogList().size();
                        CallLog callLog = inPutMessage.getCallLogList().get(size - 1);
                        callLog.setResponse("指派模式，未找到切换的场景，使用默认的场景：" + currentState.getName());
                    } else {
                        int index = aiSOP.getAnswerIndex() % aiSOP.getIntentRecognition().getAnswerList().size();
                        aiSOP.setAnswerIndex(aiSOP.getAnswerIndex() + 1);
                        String content = aiSOP.getIntentRecognition().getAnswerList().get(index);
                        Memory newMemory = new Memory(inPutMessage.getExeId(), inPutMessage.getDataId(), "System", "system", content);
                        CallLog callLog = new CallLog();
                        callLog.setResponse(content);
                        //
                        insertSessionDetailLog(new ArrayList<>(), null, null, null, callLog, inPutMessage, beginTime, false, runSopDTO, sessionObject.getExeNum());

                        // 更新对话记忆
                        aiEnvironmentService.updateMemory(inPutMessage, newMemory, sessionObject);
                        // 存放到redis缓存
                        SessionManager.addSession(userKey, sessionObject);
                        outMessage.setCallLogList(inPutMessage.getCallLogList());
                        Utils.outputStreamResult(content, runSopDTO.getDataId(), true, outMessage, response);
                        return;
                    }
                }

                if (currentAgent == null) {
                    IntentRecognition recognition = currentState.getIntentRecognition();
                    Integer type = recognition.getDefaultIntentType();
                    if (type != null && type == 2) {
                        currentAgent = currentState.getAgent(recognition.getAnswerList().get(0));
                        int size = inPutMessage.getCallLogList().size();
                        CallLog callLog = inPutMessage.getCallLogList().get(size - 1);
                        callLog.setResponse("指派模式，未找到切换的Agent，使用默认的Agent：" + currentAgent.getName());
                    } else {
                        currentState.setChatNums(currentState.getChatNums() + 1);
                        int index = currentState.getAnswerIndex() % currentState.getIntentRecognition().getAnswerList().size();
                        currentState.setAnswerIndex(currentState.getAnswerIndex() + 1);
                        String content = currentState.getIntentRecognition().getAnswerList().get(index);
                        Memory newMemory = new Memory(inPutMessage.getExeId(), inPutMessage.getDataId(), "System", "system", content);
                        // 更新对话记忆
                        aiEnvironmentService.updateMemory(inPutMessage, newMemory, sessionObject);
                        CallLog callLog = new CallLog();
                        callLog.setResponse(content);

                        //新增sop记录
                        insertSessionDetailLog(new ArrayList<>(), null, null, null, callLog, inPutMessage, beginTime, false, runSopDTO, sessionObject.getExeNum());

                        // 存放到redis缓存
                        SessionManager.addSession(userKey, sessionObject);
                        outMessage.setCallLogList(inPutMessage.getCallLogList());
                        Utils.outputStreamResult(content, runSopDTO.getDataId(), true, outMessage, response);
                        return;
                    }
                }
            } else {
                currentState = aiSOP.getCurrentState();
                currentAgent = currentState.getAgent(currentState.getCurrentAgent());
                log.info("currentAgent:{}", JSONObject.toJSONString(currentAgent));
                inPutMessage.setAgent(currentAgent);
                inPutMessage.setState(currentState);
            }

            // 获取下一步执行动作
            AgentActionBO agentExeBO = new AgentActionBO();
            agentExeBO.setAgent(currentAgent);
            agentExeBO.setMessage(inPutMessage);
            if (!inParamFlag) {
                agentExeBO.setInput(runSopDTO.getContent());
            } else {
                agentExeBO.setInput(sessionObject.getQuery());
            }
            agentExeBO.setRepeat(repeat);
            agentExeBO.setInParamFlag(inParamFlag);
            agentExeBO.setInputParamParam(runSopDTO.getParam());
            agentExeBO.setResponse(response);
            agentExeBO.setOutMessage(outMessage);
            Action action = aiAgentService.step(agentExeBO);
            Map<String, AtomicBoolean> atomicIntegerMap = SessionConnectManager.getInstance().getStoryMap();
            AtomicBoolean atomicBoolean = atomicIntegerMap.get(runSopDTO.getSessionId());
            if (atomicBoolean != null && !atomicBoolean.get()){
                SessionConnectManager.getInstance().addStopSessionId(runSopDTO.getSessionId());
                SessionConnectManager.getInstance().removeStorySessionId(runSopDTO.getSessionId());
                log.info("流程中断");
            }

            //新增提示词和sop详情日志
            long time = System.currentTimeMillis() - beginTime;
            if (!inParamFlag) {
                //判断是否有入参
                if (action != null && action.getCallLog() != null && !CollectionUtil.isEmpty(action.getCallLog().getComponentUserInPutParam())) {
                    List<ComponentInParamVO> componentVO = getComponentInParam(action.getCallLog().getComponentUserInPutParam());
                    outMessage.setComponentInParam(componentVO);
                    sessionObject.setQuery(runSopDTO.getContent());
                    SessionManager.addSession(userKey, sessionObject);
                    insertSessionDetailLog(currentState.getLabelList(), null, null, null, action.getCallLog(), inPutMessage, beginTime, currentAgent.isUser(), runSopDTO, JSONObject.toJSONString(componentVO), sessionObject.getExeNum());
                    Utils.outputStreamResult(null, runSopDTO.getDataId(), true, outMessage, response);
                    return;
                }
            }
            // 执行动作
            assert action != null;
            Memory newMemory = action.process(inPutMessage);

            outMessage.setTimeLong(time);
            outMessage.setCallEndTime(new Date());
            outMessage.setImageList(JSONObject.toJSONString(action.getCallLog().getImageList()));
            if (runSopDTO.isDebug()) {
                outMessage.setCallLogList(inPutMessage.getCallLogList());
            }
            List<BubbleComponent> bubbleComponentList = currentAgent.getBubbleComponentList();
            if (bubbleComponentList != null && bubbleComponentList.size() > 0) {
                outMessage.setBubbleList(JSONObject.toJSONString(bubbleComponentList));
            }
            outMessage.setAgentResponse(action.getCallLog().getAgentResponse());
            if (CollectionUtil.isNotEmpty(action.getCallLog().getLabelList())) {
                outMessage.setLabelList(JSONObject.toJSONString(action.getCallLog().getLabelList()));
            }

            String content = action.getAgentResult();
            outMessage.setContent(content);
            Utils.outputStreamResult(content, runSopDTO.getDataId(), true, outMessage, response);

            //新增sop记录
            insertSessionRecord(runSopDTO, inPutMessage.getSessionId(), sopStartTime);
            insertSessionDetailLog(currentState.getLabelList(), outMessage.getImageList(), outMessage.getFileList(), outMessage.getBubbleList(), action.getCallLog(), inPutMessage, beginTime, currentAgent.isUser(), runSopDTO, sessionObject.getExeNum());

            // 更新对话记忆
            aiEnvironmentService.updateMemory(inPutMessage, newMemory, sessionObject);
            sessionObject.setQuery(null);
            // 存放到redis缓存
            SessionManager.addSession(userKey, sessionObject);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("智能体执行出错:{}", e.getMessage());
            outMessage.setCallLogList(inPutMessage.getCallLogList());
            Utils.outputStreamResult(1000, "执行出错:" + e.getMessage(), true, runSopDTO.getDataId(), outMessage, response);
        } finally {
            insertPromptLog(inPutMessage, runSopDTO.getSopVersionId(), runSopDTO.getSaasAppId(), runSopDTO.getExeType(), runSopDTO.getType());
        }

    }

    @Override
    public void runSOPStream(AgentExeDTO agentExeDTO, HttpServletResponse response) {

        try {
            Thread currentThread = Thread.currentThread();
            //Long nx = JedisUtils.setNx("thread:name:" + runSopDTO.getSessionId(), currentThread.getName(), 600);
            // 控制并发，一个会话同一个时刻只能执行一个。
            /*if (nx == 0) {
                log.info("session doing,sessionId:{}", runSopDTO.getSessionId());
                Utils.outputStreamResult(1000, "对话执行中", true, runSopDTO.getDataId(), response);
                return;
            }*/
            String userKey = AgentConstant.AGENT_PREFIX + agentExeDTO.getSopId()+(agentExeDTO.isDebug()?("-" + agentExeDTO.getSopVersionId()):"")+":"+agentExeDTO.getSessionId();
            log.info("userKey:{}", userKey);

            // 存放到redis缓存 TODO
            String str = "";
            SessionObject sessionObject =SessionManager.getSession(userKey);
            if (sessionObject == null) {
                log.info("session not create,userKey:{}", userKey);
                //Utils.outputStreamResult(1000, "请先创建对话", true, agentExeDTO.getDataId(), response);
                //return;
                //默认创建会话
                startSOP(agentExeDTO);

                sessionObject =SessionManager.getSession(userKey);
            }
            SessionConnectManager.getInstance().addSessionId(agentExeDTO.getSessionId());
            log.info("userKey:{}", userKey);
            AISOP aiSOP = sessionObject.getAiSOP();
            boolean isDialogueMode = aiSOP.isDialogueMode();
            if (isDialogueMode) {
                dialogueRunSOPStream(agentExeDTO, response, sessionObject, userKey);
            } else {
                taskSOPStream(agentExeDTO, response, sessionObject, userKey);
            }
        } finally {
            //JedisUtils.del("thread:name:" + runSopDTO.getSessionId());
        }
    }

    @Override
    public void taskSOPStream(AgentExeDTO runSopDTO, HttpServletResponse response, SessionObject sessionObject, String userKey) {
        Date sopStartTime = new Date();
        AISOP aiSOP = sessionObject.getAiSOP();
        AIEnvironment aiEnvironment = sessionObject.getAiEnvironment();
        runSopDTO.setSessionId(sessionObject.getSessionId());

        // 对话处理类型，1：取消前一条回复，2：重新回答，3：重新编辑
        dealChat(runSopDTO, aiEnvironment);

        while (true) {
            long beginTime = System.currentTimeMillis();
            sessionObject.exeTotal();
            OutPutMessage outMessage = new OutPutMessage(sessionObject.getSessionId(), sessionObject.getExeNum());
            InPutMessage inPutMessage = new InPutMessage(aiEnvironment, sessionObject, userKey, runSopDTO);
            try {
                AIAgent currentAgent;
                AIState currentState;
                // 获取下一步流程
                boolean inParamFlag = runSopDTO.isInParamFlag();
                boolean repeat = runSopDTO.isRepeat();
                if (!inParamFlag && !repeat) {
                    AIState state = inPutMessage.getSop().getCurrentState();
                    AIAgent agent = state.getAgent(state.getCurrentAgent());
                    if (agent != null) {
                        agent.getExecComponentInParam().clear();
                        agent.getExecComList().clear();
                        agent.getComponentResult().clear();
                    }
                    aiSopService.next(inPutMessage, sessionObject, response);
                    //判断当前的agent是否需要参数，如果需要，直接返回，如果不需要，则继续往下走
                    currentAgent = inPutMessage.getAgent();
                    currentState = inPutMessage.getState();

                    // 判断操作流程是否结束
                    if (aiSOP.isFinished()) {
                        log.info("SOP finished!");
                        sessionObject.setExeNum(0);
                        Utils.outputStreamResult(null, runSopDTO.getDataId(), true, outMessage, response);
                        return;
                    }
                    if (currentAgent == null) {
                        log.warn("currentAgent  is null");
                        Utils.outputStreamResult(1000, "currentState  is null", true, runSopDTO.getDataId(), response);
                        return;
                    }
                    if (currentState == null) {
                        log.warn("currentState  is null");
                        Utils.outputStreamResult(1000, "currentState  is null", true, runSopDTO.getDataId(), response);
                        return;
                    }
                } else {
                    currentState = aiSOP.getCurrentState();
                    currentAgent = currentState.getAgent(currentState.getCurrentAgent());
                    inPutMessage.setAgent(currentAgent);
                    inPutMessage.setState(currentState);
                }
                // 获取下一步执行动作
                AgentActionBO agentExeBO = new AgentActionBO();
                agentExeBO.setAgent(currentAgent);
                agentExeBO.setMessage(inPutMessage);
                if (!inParamFlag) {
                    agentExeBO.setInput(runSopDTO.getContent());
                } else {

                }
                agentExeBO.setRepeat(repeat);
                agentExeBO.setInParamFlag(inParamFlag);
                agentExeBO.setInputParamParam(runSopDTO.getParam());
                agentExeBO.setResponse(response);
                agentExeBO.setOutMessage(outMessage);
                Action action = aiAgentService.step(agentExeBO);
                if (!inParamFlag) {
                    //判断是否有入参
                    if (action != null && action.getCallLog() != null && !CollectionUtil.isEmpty(action.getCallLog().getComponentUserInPutParam())) {
                        List<ComponentInParamVO> componentVO = getComponentInParam(action.getCallLog().getComponentUserInPutParam());
                        outMessage.setComponentInParam(componentVO);
                        SessionManager.addSession(userKey, sessionObject);
                        Utils.outputStreamResult(null, runSopDTO.getDataId(), true, outMessage, response);
                        return;
                    }
                }

                // 执行动作
                assert action != null;
                Memory memory = action.process(inPutMessage);

                // 更新对话记忆
                aiEnvironmentService.updateMemory(inPutMessage, memory, sessionObject);
                // 存放到redis缓存
                SessionManager.addSession(userKey, sessionObject);

                //新增提示词和sop详情日志
                long time = System.currentTimeMillis() - beginTime;

                //新增sop记录
                insertSessionRecord(runSopDTO, inPutMessage.getSessionId(), sopStartTime);
                insertSessionDetailLog(currentState.getLabelList(), null, null, null, action.getCallLog(), inPutMessage, beginTime, currentAgent.isUser(), runSopDTO, sessionObject.getExeNum());
                if (aiSOP.isDialogueMode() && !currentAgent.isUser()) {
                    outMessage.setTimeLong(time);
                    outMessage.setCallEndTime(new Date());
                    outMessage.setImageList(JSONObject.toJSONString(action.getCallLog().getImageList()));
                    outMessage.setCallLogList(inPutMessage.getCallLogList());
                    outMessage.setAgentResponse(action.getCallLog().getAgentResponse());
                    List<BubbleComponent> bubbleComponentList = currentAgent.getBubbleComponentList();
                    if (bubbleComponentList != null && bubbleComponentList.size() > 0) {
                        outMessage.setBubbleList(JSONObject.toJSONString(bubbleComponentList));
                    }
                    if (CollectionUtil.isNotEmpty(action.getCallLog().getLabelList())) {
                        outMessage.setLabelList(JSONObject.toJSONString(action.getCallLog().getLabelList()));
                    }
                    if (ObjectUtil.isEmpty(outMessage.getLabelList())) {
                        outMessage.setLabelList(JSONObject.toJSONString(currentState.getLabelList()));
                    }
                    String content = action.getAgentResult();
                    outMessage.setResponse(content);
                    Utils.outputStreamResult(content, runSopDTO.getDataId(), true, outMessage, response);
                    return;
                }
            } catch (Exception e) {
                log.error("智能体执行出错:{}", e.getMessage());
                Utils.outputStreamResult(1000, "执行出错" + e.getMessage(), true, runSopDTO.getDataId(), outMessage, response);
                return;
            } finally {
                insertPromptLog(inPutMessage, runSopDTO.getSopVersionId(), runSopDTO.getSaasAppId(), runSopDTO.getExeType(), runSopDTO.getType());
            }
        }
    }

    private List<ComponentInParamVO> getComponentInParam(List<ComponentInParam> componentUserInPutParam) {
        List<ComponentInParamVO> componentVO = new ArrayList<>();
        for (ComponentInParam entry : componentUserInPutParam) {
            ComponentInParamVO vo = new ComponentInParamVO();
            BeanUtils.copyProperties(entry, vo);
            vo.setComponentId(entry.getId());
            componentVO.add(vo);
        }
        return componentVO;
    }


    private String generateSessionId(AgentExeDTO runSopDTO) {
        return "1f567866a4b5461393694b7cb4df9c10-" + runSopDTO.getSopId() + "-" + runSopDTO.getUserId();
        //return UUID.randomUUID().toString().toLowerCase().replaceAll("-","")  + "-" + runSopDTO.getSopId() + "-" + runSopDTO.getUserId();
    }

    private void insertSessionRecord(AgentExeDTO runSopDTO, String sessionId, Date startTime) {
        try {
            Date endTime = new Date();
            //根据sessionId查询是否已有记录
            SopSessionRecord sopSessionRecord = new SopSessionRecord();
            sopSessionRecord.setSessionStartTime(startTime);
            sopSessionRecord.setSessionEndTime(endTime);
            sopSessionRecord.setSessionTimeLong(endTime.getTime() - startTime.getTime());
            sopSessionRecord.setSopId(runSopDTO.getSopId());
            sopSessionRecord.setUserId(runSopDTO.getUserId());
            sopSessionRecord.setSessionId(sessionId);
            sopSessionRecord.setSopVersionId(runSopDTO.getSopVersionId());
            sopSessionRecord.setExeType(runSopDTO.getExeType());
            sopSessionRecord.setSaasAppId(runSopDTO.getSaasAppId());
            sopSessionRecord.setType(runSopDTO.getType());
            sopSessionRecord.setSessionEndTime(endTime);
            sopSessionRecord.setSessionTimeLong(endTime.getTime() - sopSessionRecord.getSessionStartTime().getTime());
            //producer.sendMsg("ENGINE_TEMPLATE", "session_record", UUID.randomUUID().toString(), JSONObject.toJSONString(sopSessionRecord));
        } catch (Exception e) {
            log.error("新增提示词日志Record报错,{}", e.getMessage(), e);
        }
    }

    private void insertSessionDetailLog(List<String> labelList, String imageList, String fileList, String bubbleList, CallLog callLog, InPutMessage message, Long beginTime, boolean isUser, AgentExeDTO runSopDTO, int exeId) {

        insertSessionDetailLog(labelList, imageList, fileList, bubbleList, callLog, message, beginTime, isUser, runSopDTO, null, exeId);
    }

    private void insertSessionDetailLog(List<String> labelList, String imageList, String fileList, String bubbleList, CallLog callLog, InPutMessage message, Long beginTime, boolean isUser, AgentExeDTO runSopDTO, String componentInParam, int exeId) {

        try {
            SopSessionDetails sopSessionDetails = new SopSessionDetails();
            sopSessionDetails.setChatContent(callLog.getResponse());
            sopSessionDetails.setAgentResponse(callLog.getAgentResponse());
            sopSessionDetails.setSessionId(message.getSessionId());
            sopSessionDetails.setChatUser(isUser ? 1 : 2);
            sopSessionDetails.setExeId(exeId);
            sopSessionDetails.setSopVersionId(runSopDTO.getSopVersionId());
            sopSessionDetails.setExeType(runSopDTO.getExeType());
            sopSessionDetails.setSaasAppId(runSopDTO.getSaasAppId());
            sopSessionDetails.setUserId(message.getUserId());
            sopSessionDetails.setComponentInParam(componentInParam);
            sopSessionDetails.setChatTime(new Date(beginTime));

            if (callLog.getResponse() != null && callLog.getResponse().startsWith("User:")) {
                sopSessionDetails.setChatContent(callLog.getResponse().substring(5));
            }

            if (message.getSop() != null) {
                AISOP aisop = message.getSop();
                sopSessionDetails.setSopId(aisop.getId());
                sopSessionDetails.setSopName(aisop.getName());
            }
            if (message.getState() != null) {
                AIState aiState = message.getState();
                sopSessionDetails.setStateId(aiState.getId());
                sopSessionDetails.setStateName(aiState.getName());
            }
            if (message.getAgent() != null) {
                AIAgent agent = message.getAgent();
                sopSessionDetails.setAgentId(agent.getId());
                sopSessionDetails.setAgentName(agent.getName());
                sopSessionDetails.setAgentRole(agent.getRole());
            }
            if (ObjectUtil.isNotEmpty(imageList)) {
                sopSessionDetails.setImageList(imageList);
            }
            if (ObjectUtil.isNotEmpty(fileList)) {
                sopSessionDetails.setFileList(fileList);
            }
            if (ObjectUtil.isNotEmpty(bubbleList)) {
                sopSessionDetails.setBubbleList(bubbleList);
            }
            if (CollectionUtil.isNotEmpty(callLog.getLabelList())) {
                sopSessionDetails.setLabelList(JSONObject.toJSONString(callLog.getLabelList()));
            } else {
                if (CollectionUtil.isNotEmpty(labelList)) {
                    sopSessionDetails.setLabelList(JSONObject.toJSONString(labelList));
                }
            }
            if (CollectionUtil.isNotEmpty(runSopDTO.getParam())) {
                sopSessionDetails.setInParam(JSONObject.toJSONString(runSopDTO.getParam()));
                //将入参更新到上一条user日志里
                SopSessionDetails logParam = new SopSessionDetails();
                logParam.setSessionId(message.getSessionId());
                logParam.setChatUser(1);
                logParam.setSopId(message.getSop().getId());
            }

            log.info("新增提示词日志Detail,sessionId:{},data:{}", message.getSessionId(), JSONObject.toJSONString(sopSessionDetails));
            //producer.sendMsg("ENGINE_TEMPLATE", "session_detail", UUID.randomUUID().toString(), JSONObject.toJSONString(sopSessionDetails));
        } catch (Exception e) {
            log.error("新增提示词日志Detail报错:{}", e.getMessage(), e);
        }
    }


    private void insertPromptLog(InPutMessage message, Long sopVersionId, Long saasAppId, Integer exeType, Integer type) {

        if (ObjectUtil.isAllNotEmpty(message, message.getCallLogList())) {

            List<PromptLog> promptLogList = new ArrayList<>();
            for (CallLog callLog : message.getCallLogList()) {
                PromptLog promptLog = BeanUtil.copyProperties(callLog, PromptLog.class);
                promptLog.setSessionId(message.getSessionId() + "-" + message.getExeId());
                promptLog.setSopVersionId(sopVersionId);
                promptLog.setSaasAppId(saasAppId);
                promptLog.setExeType(exeType);
                promptLog.setType(type);
                if (message.getSop() != null) {
                    promptLog.setSopId(message.getSop().getId());
                    promptLog.setSopName(message.getSop().getName());
                }
                if (message.getState() != null) {
                    promptLog.setStateId(message.getState().getId());
                    promptLog.setStateName(message.getState().getName());
                }
                if (message.getAgent() != null) {
                    promptLog.setAgentId(message.getAgent().getId());
                    promptLog.setAgentName(message.getAgent().getName());
                }
                promptLogList.add(promptLog);
            }
            try {
                //producer.sendMsg("ENGINE_TEMPLATE", "prompt_log", UUID.randomUUID().toString(), JSONObject.toJSONString(promptLogList));
            } catch (Exception e) {
                log.info("上传数据失败：{},{}", JSONObject.toJSONString(promptLogList), e.getMessage());
            }
        }
    }
}
